package com.universalInterface.lims_interface.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.universalInterface.common.exception.BusinessException;
import com.universalInterface.common.result.ApiCode;
import com.universalInterface.common.utils.SaltMD5Util;
import com.universalInterface.lims_interface.entity.InterfaceUser;
import com.universalInterface.lims_interface.entity.LabInfo;
import com.universalInterface.lims_interface.mapper.InterfaceUserMapper;
import com.universalInterface.lims_interface.mapper.LabInfoMapper;
import com.universalInterface.lims_interface.service.IInterfaceUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-12-20
 */
@RequiredArgsConstructor
@Service
public class InterfaceUserServiceImpl implements IInterfaceUserService {

	private final InterfaceUserMapper userMapper;

	private final LabInfoMapper labInfoMapper;

	@Override
	public InterfaceUser save(InterfaceUser entity) {
		QueryWrapper query = new QueryWrapper();
		// 查询用户是否存在
		query.eq("user_name", entity.getUserName());
		Long count = userMapper.selectCount(query);
		if (count > 0) {
			throw new BusinessException(500, "用户名重复，请重新输入");
		}
		// 查询实验室是否存在
		query.clear();
		query.eq("lab_guid", entity.getLabGuid());
		LabInfo labInfo = labInfoMapper.selectOne(query);
		if (labInfo == null) {
			throw new BusinessException(500, "该实验室不存在");
		}
		entity.setLabName(labInfo.getLabName());
		entity.setPassWord(SaltMD5Util.encrypt(entity.getPassWord()));
		int i = userMapper.insert(entity);
		return entity;
	}

	@Override
	public Integer deleteById(Long id) {
		return userMapper.deleteById(id);
	}

	@Override
	public InterfaceUser login(InterfaceUser entity) {
		QueryWrapper query = new QueryWrapper();
		query.eq("user_name", entity.getUserName());
		if (StrUtil.isNotBlank(entity.getInterfaceType())) {
			query.eq("interface_type", entity.getInterfaceType());
		}
		if (StrUtil.isNotBlank(entity.getForm())) {
			query.eq("form", entity.getForm());
		}
		InterfaceUser o = userMapper.selectOne(query);
		if (o == null) {
			throw new BusinessException(ApiCode.USER_NOT＿EXIST);
		}
		// 验证密码
		if (!SaltMD5Util.verify(entity.getPassWord(), o.getPassWord())) {
			throw new BusinessException(ApiCode.PASSWORD_ERROR);
		}
		return o;
	}

}
